// app.js
import api from './utils/request.js'
var myaudio = wx.getBackgroundAudioManager()
App({
  globalData: {
    userInfo: null,
    host: 'http://192.168.0.26:8081',
    audiolist: [
    ],
    // 是否正在播放
    isPlaying: false,
    // 总时长
    allTime: "00:00",
    // 处理好的当前时间
    nowTime: "00:00",
    // 当前时间（秒）
    nowTimes: "",
    // 进度
    audioTime: "0",
    // 当前图片
    URL: "",
    // 当前播放歌曲序号
    idx: 0,
    // 播放方式
    PlayMode: 1,
    // 当前歌曲名
    nowSongName: "",
    // 当前歌手名
    nowArtist: "",
    isCanplay: false,
    isGetData: false,
    isWrong: false
  },

  // 初始化当前音频
  Initialization() {
    if (this.globalData.audiolist.length != 0) {
      myaudio.title = this.globalData.audiolist[this.globalData.idx].songName;
      myaudio.epname = this.globalData.audiolist[this.globalData.idx].album;
      myaudio.singer = this.globalData.audiolist[this.globalData.idx].artist;
      myaudio.coverImgUrl = this.globalData.audiolist[this.globalData.idx].coverimg;
      myaudio.src = this.globalData.audiolist[this.globalData.idx].audiosrc;
      // 取消自动播放
      myaudio.onPlay(() => {
        if (!this.globalData.isPlaying) {
          myaudio.pause();
        }
      })
      this.globalData.URL = this.globalData.audiolist[this.globalData.idx].coverimg
      this.globalData.nowSongName = this.globalData.audiolist[this.globalData.idx].songName
      this.globalData.nowArtist = this.globalData.audiolist[this.globalData.idx].artist
      this.globalData.audioTime = "0"
    }
    // 获取音频的总时长
    this.GetAudioLength();
    this.play();
    this.globalData.isGetData = true;

  },

  // 获取音频总时长
  GetAudioLength() {
    myaudio.onCanplay(() => {
      myaudio.duration;
      setTimeout(() => {
        var als = Math.ceil(myaudio.duration);
        var s = String(als % 60);
        var m = String(Math.floor(als / 60));
        var mm = m.length == 1 ? '0' + m : m;
        var ss = s.length == 1 ? '0' + s : s;
        this.globalData.allTime = `${mm}:${ss}`;
        this.globalData.isCanplay = true;
      }, 100)
    })
  },

  // 设置当前时间、进度条
  currentTime() {
    var time = setInterval(() => {
      var currentTime = myaudio.currentTime
      if (!this.globalData.isPlaying) {
        clearInterval(time)
      }
      if (currentTime < 0.5) {
        var als = '0'
      } else {
        var als = Math.ceil(currentTime);
      }
      var m = String(Math.floor(als / 60));
      var s = String(als % 60);
      var mm = m.length == 1 ? '0' + m : m;
      var ss = s.length == 1 ? '0' + s : s;
      var times = parseInt(100 * currentTime / myaudio.duration);

      // if (currentTime - this.globalData.nowTimes < 1 && currentTime - this.globalData.nowTimes > 0.9) {
      //   this.globalData.nowTimes = currentTime
      //   this.globalData.nowTime = `${mm}:${ss}`
      // } else {

      this.globalData.nowTimes = currentTime
      this.globalData.nowTime = `${mm}:${ss}`
      this.globalData.audioTime = times
      // }
    }, 1000)
  },

  // 播放方式
  playMode(val) {
    val = Number(val);
    if (val == 2) {
      val = -1;
    }
    this.globalData.PlayMode = val + 1;
    wx.setStorageSync('PlayMode', val + 1);
  },

  // 播放
  play(index) {
    if (index != undefined) {
      this.globalData.idx = index;
      this.Initialization();
    }
    this.globalData.isPlaying = true;
    myaudio.play();
    this.currentTime();
  },

  // 暂停
  pause() {
    this.globalData.isPlaying = false;
    myaudio.pause();
  },

  // 进度条拖动事件
  sliderChange(value) {
    this.globalData.audioTime = value;
    var values = parseInt(value * myaudio.duration / 100)
    // 更改状态
    this.globalData.isPlaying = true

    //调用seek方法跳转歌曲时间
    myaudio.seek(values);
    //播放歌曲
    this.play();
  },

  // 上一曲
  down() {
    if (this.globalData.idx <= 0) {
      this.globalData.idx = this.globalData.audiolist.length - 1
    } else {
      this.globalData.idx = this.globalData.idx - 1
    }
    // 初始化
    this.Initialization();

    // 播放
    this.play();
  },

  // 下一曲
  next() {
    if (this.globalData.PlayMode == 2) {
      this.globalData.idx = this.RandomNum(0, this.globalData.audiolist.length - 1)
    } else {
      if (this.globalData.idx >= this.globalData.audiolist.length - 1) {
        this.globalData.idx = 0;
      } else {
        this.globalData.idx = this.globalData.idx + 1;
      }
    }
    // 初始化
    this.Initialization();

    // 播放
    this.play();
  },

  // 获取随机数
  RandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.round(Rand * Range);
    return num;
  },

  // 监听方法
  watch(method) {
    var obj = this.globalData;
    Object.defineProperty(obj, "isCanplay", {
      set: function (value) {
        method(value);
      }
    })
  },

  // 监听数据更新
  watchIsGetData(method) {
    var obj = this.globalData;
    Object.defineProperty(obj, "isGetData", {
      set: function (value) {
        method(value);
      }
    })
  },

  // 监听音频报错
  watchIsWrong(method) {
    var obj = this.globalData;
    Object.defineProperty(obj, "isWrong", {
      set: function (value) {
        method(value);
      }
    })
  },

  pdr(list) {
    let arr = [];
    for (let i = 0; i < list.length; i++) {
      arr[i] = {};
      arr[i].id = list[i].id;
      arr[i].musicCode = list[i].musicCode;
      arr[i].album = list[i].album.albumName;
      arr[i].coverimg = list[i].imgUrl;
      arr[i].source = list[i].musicLyric;
      arr[i].songName = list[i].musicName;
      if (list[i].singer != null) {
        arr[i].artist = list[i].singer.singerName;
      }
      arr[i].audiosrc = list[i].url;
      arr[i].musicLyric = list[i].musicLyric;
    }

    return arr
    // this.globalData.audiolist = arr
  },

  // 获取播放列表数据
  getPlayListData(list, muId) {
    this.globalData.audiolist = this.pdr(list);
    if (muId != undefined) {
      for (let i = 0; i < this.globalData.audiolist.length; i++) {
        if (this.globalData.audiolist[i].id == muId) {
          this.globalData.idx = i;
          break;
        }
      }
    } else {
      this.globalData.idx = 0;
    }

    // 初始化
    this.Initialization();

    this.play();

    // wx.request({
    //   url: this.globalData.host + `/songSheet/getSongSheetById?id=${id}`,
    //   method: "get",
    //   success: (res) => {
    //     var list = res.data.data.music;

    //     this.globalData.audiolist = this.pdr(list);

    //     for (let i = 0; i < this.globalData.audiolist.length; i++) {
    //       if (this.globalData.audiolist[i].id == muId) {
    //         this.globalData.idx = i;
    //         break;
    //       }
    //     }

    //     // 初始化
    //     this.Initialization();
    //   }
    // })
  },

  // 添加一首歌
  getOneMusic(id) {
    wx.request({
      url: this.globalData.host + `/music/getMusicById?id=${id}`,
      method: "get",
      success: (res) => {
        var list = [res.data.data];

        this.globalData.audiolist.push(this.pdr(list)[0])

        this.globalData.idx = this.globalData.audiolist.length - 1;

        this.Initialization();
        this.isCanplay = true;
        this.play();
      }
    })

  },

  // 删除
  del(idx) {
    this.globalData.audiolist.splice(idx, 1);
    this.globalData.isCanplay = true;
  },

  // 清空播放列表
  deleteAll() {
    this.globalData.audiolist = [];
    this.pause();
    myaudio.stop();
  },

  onLaunch() {


    // 播放方式
    var modes = wx.getStorageSync('PlayMode');
    if (modes) {
      this.globalData.PlayMode = modes;
    }

    // 音频自然播放结束时触发
    myaudio.onEnded(() => {
      // 判断当前播放方式
      switch (this.globalData.PlayMode) {
        case 0:
          // 循环列表
          this.next();
          break;
        case 1:
          // 单曲循环
          // 初始化
          this.Initialization();
          break;
        case 2:
          // 随机播放
          let index = this.RandomNum(0, this.globalData.audiolist.length - 1)
          this.globalData.idx = index;
          this.Initialization();
          break;
      }
    })

    // 音乐加载报错
    myaudio.onError(() => {
      this.globalData.isPlaying = false;
      this.globalData.isWrong = true;
      this.pause();
    })


    // 获取数据
    // this.getPlayListData(1, 497);

    // this.getOneMusic(49);
  },
})
export default myaudio
